<?php

abstract class View_Admin_FormLayout
{
    /**
     * 渲染一个表单
     *
     * @param QContext $context
     * @param QForm $form
     * @param boolean $return
     */
    static function render(QContext $context, QForm $form, $return = false)
    {
        $error_messages = $form->error_messages;
        if (!is_array($error_messages))
        {
            $error_messages = array();
        }

        $id = $form->id();
        $action = htmlspecialchars($form->action);
        $enctype = $form->enctype;

        $out = <<<EOT

<form class="editform" name="{$id}" id="{$id}" action="{$action}" method="post" enctype="{$enctype}">
<table>
  

EOT;

        foreach ($form as $item)
        {
            $out .= self::_renderItem($context, $item, $error_messages);
        }

        $out .= <<<EOT


<tr class="nobg">
<td>
<input type="submit" class="btn" name="btnsubmit" value="提交"  />

EOT;

        foreach ($form as $item)
        {
            if ($item->type() == 'hidden')
            {
                $out .= $item->render($context, true);
                $out .= "\n";
            }
        }

        $out .= <<<EOT

</td>
<td></td>
</tr>

</table>

</form>

EOT;

        if (!$return)
        {
            echo $out;
            $out = null;
        }

        return $out;
    }

    /**
     * 渲染一个表单项目
     *
     * @param QContext $context
     * @param QForm_Item_Abstract $item
     * @param array $error_messages
     *
     * @return string
     */
    protected static function _renderItem(QContext $context, QForm_Item_Abstract $element, array $error_messages)
    {
        $out = '';

        if ($element->type() != 'hidden')
        {
            $out .= "<tr>\n<td class=\"input\">\n";
            $id = $element->id();
            $label = h($element->label);

            if ($label)
            {
                $out .= "<label for=\"{$id}\">{$label}";
                if ($element->req)
                {
                    $out .= '<span class="req">*</span>';
                }
                $out .= "</label>\n";
            }

            $description = $element->description;
            $element->unsetProps('label, description, req');
            $out .= $element->render($context, true);

            $out .= "\n</td>\n<td>\n<span class=\"descr\">";
            $out .= nl2br(htmlspecialchars($description));
            $out .= "</span>\n";

            if (isset($error_messages[$id]))
            {
                $out .= "<span class=\"error\">";
                $msg = $error_messages[$id];
                if (is_array($msg))
                {
                    $msg = implode(', ', $msg);
                }
                $out .= nl2br(htmlspecialchars($msg)) . "</span>\n";
            }

            $out .= "</td>\n</tr>\n\n";
        }

        return $out;
    }

}

